package com.congxing.bi.util.security;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

import com.sun.mail.util.BASE64DecoderStream;

public class DecryptUtil {
	/**
	 * 
	 * @param cipherByte
	 * @param key
	 * @param algorithm
	 * @return byte[]
	 * @throws SecurityException
	 */
	public static byte[] decrypt(byte[] cipherByte, SecretKey key, String algorithm) throws SecurityException{
		byte[] plainByte = null;
		try{
			SecureRandom sr = new SecureRandom();
			Cipher cipher = Cipher.getInstance( algorithm );
	        cipher.init(Cipher.DECRYPT_MODE,key,sr);
	        plainByte = cipher.doFinal( cipherByte );
		} catch (Exception ex){
			throw new SecurityException(ex);
		}
		return plainByte;
	}
	/**
	 * 
	 * @param cipherByte
	 * @param key
	 * @return byte[]
	 * @throws SecurityException
	 */
	public static byte[] decryptWithDES(byte[] cipherByte,SecretKey key) throws SecurityException{
		return decrypt(cipherByte,key,SecurityKey.DES);
	}
	/**
	 * 
	 * @param cipherString
	 * @param key
	 * @param algorithm
	 * @return byte[]
	 * @throws SecurityException
	 */
	public static byte[] decryptFromString(String cipherString, SecretKey key, String algorithm) throws SecurityException{
		return decrypt(BASE64DecoderStream.decode(cipherString.getBytes()),key,algorithm);
	}
	/**
	 * 
	 * @param cliperString
	 * @param keyPassword
	 * @param algorithm
	 * @return String
	 * @throws SecurityException
	 */
	public static String decryptFromString(String cliperString,String keyPassword,String algorithm) throws SecurityException{		
		return new String(decryptFromString(cliperString,SecurityKey.createKeyUsePassword(keyPassword,algorithm),algorithm));
	}
	/**
	 * 
	 * @param cipherString
	 * @param key
	 * @return byte[]
	 * @throws SecurityException
	 */
	public static byte[] decryptFromStringWithDES(String cipherString, SecretKey key)  throws SecurityException{
		return decryptFromString(cipherString,key,SecurityKey.DES);
	}
	/**
	 * 
	 * @param cipherString
	 * @param keyPassword
	 * @return String
	 * @throws SecurityException
	 */
	public static String decryptFromStringWithDES(String cipherString,String keyPassword)  throws SecurityException{
		return decryptFromString(cipherString,keyPassword,SecurityKey.DES);
	}
}
